﻿#include "FontScrollWidget.h"
#include <QTimer>
#include <QPainter>
#include <QVBoxLayout>
#include <QScreen>
#include "Defs.h"


// FontScrollWidget 实现
FontScrollWidget::FontScrollWidget(QWidget* parent)
    : QWidget(parent)
    , m_isDragging(false)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground, false);
    setFixedSize(300 + m_windowMargin * 2, 400 + m_windowMargin * 2);

    // 初始化标题栏区域
    m_titleBarRect = QRect(m_contentMargin, m_contentMargin, width() - m_windowMargin * 2, m_titleBarHeight);

    // 创建关闭按钮
    m_closeButton = new QPushButton("×", this);
    m_closeButton->setFixedSize(20, 20);
    m_closeButton->setStyleSheet(R"(
        QPushButton {
            color: #666;
            background: transparent;
            border: none;
            border-radius: 2px;
            font-size: 16px;
        }
        QPushButton:hover {
            background: #ff4444;
            color: white;
        }
    )");
    connect(m_closeButton, &QPushButton::clicked, this, &FontScrollWidget::onCloseButtonClicked);

    // 创建搜索框
    m_searchEdit = new QLineEdit(this);
    m_searchEdit->setPlaceholderText("搜索字体...");
    m_searchEdit->setClearButtonEnabled(false); // 我们使用自定义的清除按钮
    m_searchEdit->setStyleSheet(R"(
        QLineEdit {
            border: 1px solid #ddd;
            border-radius: 3px;
            padding: 4px 8px;
            background: white;
            margin: 2px 4px;
        }
        QLineEdit:focus {
            border-color: #4d90fe;
        }
    )");
    //m_searchEdit->setFixedHeight(45);
    connect(m_searchEdit, &QLineEdit::textChanged, this, &FontScrollWidget::onSearchTextChanged);

    // 创建清除搜索按钮
    m_clearSearchButton = new QPushButton("×", this);
    m_clearSearchButton->setFixedSize(20, 20);
    m_clearSearchButton->setStyleSheet(R"(
        QPushButton {
            color: #999;
            background: transparent;
            border: none;
            border-radius: 2px;
            font-size: 12px;
        }
        QPushButton:hover {
            background: #e0e0e0;
            color: #666;
        }
    )");
    m_clearSearchButton->setVisible(false); // 初始隐藏
    connect(m_clearSearchButton, &QPushButton::clicked, this, &FontScrollWidget::onClearSearchClicked);

    // 创建列表控件
    m_listWidget = new QListWidget(this);
    m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_listWidget->setVerticalScrollMode(QListWidget::ScrollPerPixel);
    m_listWidget->setMouseTracking(true);

    // 初始化延迟加载计时器
    m_loadTimer = new QTimer(this);
    m_loadTimer->setSingleShot(true);
    m_loadTimer->setInterval(50);  // 50ms延迟，避免频繁触发
    connect(m_loadTimer, &QTimer::timeout, this, &FontScrollWidget::loadVisibleFonts);

    // 连接滚动条信号
    connect(m_listWidget->verticalScrollBar(), &QScrollBar::valueChanged,
        this, &FontScrollWidget::onScrollValueChanged);

    // 初始化字体列表（不立即加载字体）
    initializeFontList();

    connect(m_listWidget, &QListWidget::itemClicked, this, &FontScrollWidget::onItemClicked);

    // 调整控件位置
    adjustWidgetHeight();
}

FontScrollWidget::~FontScrollWidget()
{
}

void FontScrollWidget::initializeFontList()
{
    // 获取所有字体家族名称
    QFontDatabase fontDatabase;
    m_fontFamilies = fontDatabase.families();
    m_fontFamilies.sort(); // 为了二分做铺垫
    m_filteredFontFamilies = m_fontFamilies; // 初始时显示所有字体

    // 清空已加载字体记录
    m_loadedFonts.clear();

    // 更新字体列表显示
    updateFontList();
}

void FontScrollWidget::updateFontList()
{
    m_listWidget->clear();
    m_loadedFonts.clear();

    // 添加过滤后的字体项
    for (const QString& fontFamily : m_filteredFontFamilies) {
        QListWidgetItem* item = new QListWidgetItem(fontFamily);
        m_listWidget->addItem(item);
    }

    // 延迟加载可视区域的字体
    QTimer::singleShot(100, this, &FontScrollWidget::loadVisibleFonts);
}

void FontScrollWidget::onSearchTextChanged(const QString& text)
{
    // 更新清除按钮的可见性
    m_clearSearchButton->setVisible(!text.isEmpty());

    if (text.isEmpty()) {
        // 如果搜索文本为空，显示所有字体
        m_filteredFontFamilies = m_fontFamilies;
    }
    else {
        // 过滤字体列表
        m_filteredFontFamilies.clear();
        QString lowerText = text.toLower();
        for (const QString& fontFamily : m_fontFamilies) {
            if (fontFamily.toLower().contains(lowerText)) {
                m_filteredFontFamilies.append(fontFamily);
            }
        }
    }

    // 更新列表显示
    updateFontList();
}

void FontScrollWidget::onClearSearchClicked()
{
    m_searchEdit->clear();
    m_clearSearchButton->setVisible(false);
}

void FontScrollWidget::loadVisibleFonts()
{
    if (!m_listWidget->count()) return;

    // 获取可视区域的范围
    QRect visibleRect = m_listWidget->viewport()->rect();
    QModelIndex firstVisible = m_listWidget->indexAt(visibleRect.topLeft());
    QModelIndex lastVisible = m_listWidget->indexAt(visibleRect.bottomLeft());

    if (!firstVisible.isValid() || !lastVisible.isValid()) return;

    int start = firstVisible.row();
    int end = lastVisible.row();

    // 扩展可视区域上下各5个项，预加载
    start = qMax(0, start - 5);
    end = qMin(m_listWidget->count() - 1, end + 5);

    // 加载可视区域内的字体
    for (int i = start; i <= end; ++i) {
        QListWidgetItem* item = m_listWidget->item(i);
        if (item && !m_loadedFonts.contains(item->text())) {
            applyFontToItem(item);
            m_loadedFonts.insert(item->text());
        }
    }
}

void FontScrollWidget::applyFontToItem(QListWidgetItem* item)
{
    if (!item) return;

    QString fontFamily = item->text();
    QFont font;
    font.setFamily(fontFamily);
    font.setPointSize(10);

    // 检查字体是否可用
    QFontDatabase fontDatabase;
    if (fontDatabase.families().contains(fontFamily)) {
        item->setFont(font);
    }
}

void FontScrollWidget::onScrollValueChanged(int value)
{
    Q_UNUSED(value)
        // 延迟加载，避免滚动时频繁触发
        m_loadTimer->start();
}

void FontScrollWidget::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);
    QPainter painter(this);

    // 绘制标题栏背景
    painter.fillRect(m_titleBarRect, QColor(245, 245, 245));

    // 绘制标题栏文字
    painter.setPen(QColor(100, 100, 100));
    painter.drawText(5, 0, m_titleBarRect.width() - 30, m_titleBarRect.height(),
        Qt::AlignVCenter, "字体列表");

    // 绘制标题栏与内容区的分隔线
    painter.setPen(QColor(200, 200, 200));
    painter.drawLine(0, m_titleBarHeight - 1, width(), m_titleBarHeight - 1);
}

void FontScrollWidget::resizeEvent(QResizeEvent* event)
{
    m_titleBarRect.setWidth(width());
    m_closeButton->move(width() - 24, 2);

    // 调整搜索框和列表的位置
    adjustWidgetHeight();

    QWidget::resizeEvent(event);

    // 大小改变时重新加载可视字体
    QTimer::singleShot(100, this, &FontScrollWidget::loadVisibleFonts);
}

void FontScrollWidget::adjustWidgetHeight()
{
    int searchBarTop = m_titleBarHeight + 2;

    // 设置搜索框位置
    m_searchEdit->setGeometry(4, searchBarTop, width() - 32, m_searchBarHeight - 4);

    // 设置清除按钮位置
    m_clearSearchButton->move(width() - 24, searchBarTop + (m_searchBarHeight - 16) / 2);

    // 设置列表控件位置
    int listTop = searchBarTop + m_searchBarHeight;
    int listHeight = height() - listTop;
    m_listWidget->setGeometry(0, listTop, width(), listHeight);
}

int FontScrollWidget::binarySearchFont(const QString& fontFamily)
{
    int left = 0;
    int right = m_filteredFontFamilies.size() - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        int cmp = QString::compare(m_filteredFontFamilies[mid], fontFamily, Qt::CaseInsensitive);

        if (cmp == 0) {
            return mid;  // 找到精确匹配
        }
        else if (cmp < 0) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }

    return -1;  // 未找到
}

void FontScrollWidget::scrollToFont(const QFont& font)
{
    QString fontFamily = font.family();

    // 使用二分查找在过滤列表中定位
    int index = binarySearchFont(fontFamily);

    if (index == -1) {
        // 字体不在当前过滤列表中，清除搜索显示所有字体
        if (!m_searchEdit->text().isEmpty()) {
            m_searchEdit->clear();
            m_clearSearchButton->setVisible(false);
            m_filteredFontFamilies = m_fontFamilies;
            updateFontList();

            // 在完整列表中再次查找
            index = binarySearchFont(fontFamily);
        }
    }

    if (index != -1 && index < m_listWidget->count()) {
        QListWidgetItem* item = m_listWidget->item(index);
        if (item) {
            // 滚动到该项（居中显示）
            m_listWidget->scrollToItem(item, QAbstractItemView::PositionAtCenter);

            // 设置为当前选中项
            m_listWidget->setCurrentItem(item);

            // 确保该字体已加载显示
            if (!m_loadedFonts.contains(fontFamily)) {
                applyFontToItem(item);
                m_loadedFonts.insert(fontFamily);
            }

            // 延迟加载周围的字体
            QTimer::singleShot(100, this, &FontScrollWidget::loadVisibleFonts);
        }
    }
}

void FontScrollWidget::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_titleBarRect.contains(event->pos()) &&
            !m_closeButton->geometry().contains(event->pos())) {
            m_dragStartPos = event->pos();
            m_isDragging = true;
            setCursor(QCursor(Qt::ClosedHandCursor));
            event->accept();
        }
        else {
            m_isDragging = false;
            QWidget::mousePressEvent(event);
        }
    }
    else {
        QWidget::mousePressEvent(event);
    }
}

void FontScrollWidget::mouseMoveEvent(QMouseEvent* event)
{
    if (m_isDragging && (event->buttons() & Qt::LeftButton)) {
        QPoint newPos = event->globalPos() - m_dragStartPos;
        move(newPos);
        event->accept();
    }
    else {
        QWidget::mouseMoveEvent(event);
    }
}

void FontScrollWidget::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton && m_isDragging) {
        m_isDragging = false;
        setCursor(QCursor(Qt::ArrowCursor));
        snapToParentEdge();
        event->accept();
    }
    else {
        QWidget::mouseReleaseEvent(event);
    }
}

void FontScrollWidget::closeEvent(QCloseEvent* event)
{
    event->ignore();
    hide();
    emit hidden();
}

void FontScrollWidget::onCloseButtonClicked()
{
    hide();
    emit hidden();
}

void FontScrollWidget::snapToParentEdge()
{
    // 磁吸逻辑可以根据需要实现
}

void FontScrollWidget::onItemClicked(QListWidgetItem* item)
{
    //发射对应字体
    if (!item) return;

    // 创建字体对象并发射信号
    QFont font;
    font.setFamily(item->text());
    font.setPointSize(10); // 可以调整为合适的字号

    emit fontChanged(font);
    hide();
    emit hidden();
}